<template>
  <div>
    <div class="col-md-12">
      <form class="form-inline">
        <div class="form-group col-md-3">
          <label for="name" class="control-label">设备编号&nbsp;</label>
          <input
            type="text"
            style="width:190px"
            autocomplete="off"
            class="form-control"
            id="device_id"
            placeholder="请输入设备号"
            onclick="showMenudevicesingle(this)"
          />
          <loaddevicesingle></loaddevicesingle>
        </div>

        <div class="form-group col-md-6">
          <label for="name" class="control-label">日期&nbsp;</label>
          <input
            type="text"
            style
            class="input form-control"
            readonly="readonly"
            id="time"
            autocomplete="off"
            placeholder="请选择日期"
          />

          <label for="name" class="control-label">时段</label>
          <select id="hourk" class="form-control"></select>
          <select id="hourj" class="form-control"></select>
          <button type="button" class="btn btn-primary">查询</button>
        </div>
      </form>
    </div>

    <div class="col-md-12">
      <div id="controller" align="center" style="display:">
        <input id="follow" type="checkbox" />
        <span style="font-size:12px;">画面跟随</span>
        <input
          id="play"
          type="button"
          class="btn btn-success"
          value="播放"
          onclick="play();"
          disabled="true"
        />
        <input
          id="pause"
          type="button"
          class="btn btn-warning"
          value="暂停"
          onclick="pause();"
          disabled
        />
        <input
          id="reset"
          type="button"
          class="btn btn-primary"
          value="重置"
          onclick="reset()"
          disabled
        />
      </div>
      <div class="col-md-6 allmap" style="margin:5px 0;" id="container"></div>
    </div>
  </div>
</template>
<script>
import "../../../../static/js/time/jquery.date_input.pack.js";

import loaddevicesingle from "@/views/tree/devicesingle.vue";

export default {
  data() {
    return {};
  },
  created() {},
  methods: {
    //坐标转换完之后的回调函数
  },
  components: {
    loaddevicesingle: loaddevicesingle
  },
  mounted() {
    this.$nextTick(function() {
      //  alert( this.drawMap());
      // this.drawMap();
    });
  }
};

// window.bd_encrypt=function(gg_lon, gg_lat){
//                 var X_PI = Math.PI * 3000.0 / 180.0;
//                 var x = gg_lon, y = gg_lat;
//                 var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * X_PI);
//                 var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * X_PI);
//                 var bd_lon = z * Math.cos(theta) + 0.0065;
//                 var bd_lat = z * Math.sin(theta) + 0.006;
//                 return {
//                     bd_lat: bd_lat,
//                     bd_lon: bd_lon
//                 };
// }
//百度地图API功能
//异步加载地图
$(function() {
  $("#time").date_input();
  var d = new Date();
  var sd = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
  $("#time").val(sd);
  init();
$("#menuContentdevicesingle").css("margin","")
$("#menuContentdevicesingle").css("margin","0px 64px")
});
var points = [];
var map; //百度地图对象
var car; //汽车图标
var label; //信息标签
var centerPoint;
var timer; //定时器
var index = 0; //记录播放到第几个point
var followChk, playBtn, pauseBtn, resetBtn; //几个控制按钮
var vali = 0;
window.init = function() {
  if ($("#device_id").val().length > 0) {
    $.ajax({
      type: "POST",
      url:
        domain.testUrl +
        "/Threeinjection/DeviceManagement/queryDeviceGRRSSpeedInfo",
      data: {
        sessionid: sessionStorage.getItem("sid"),
        devicenumber: $("#device_id").val(),
        startTime:
          $("#time").val() +
          " " +
          $("#hourk")
            .find("option:selected")
            .text(),
        endTime:
          $("#time").val() +
          " " +
          $("#hourj")
            .find("option:selected")
            .text()
      },
      async: false,
      //data:{sessionid:sessionStorage.getItem("sid"),devicenumber:"",startTime:"",endTime:""},
      success: function(response) {
        //console.log(response);
        var data = JSON.parse(response);
        if (data.length == 0) {
          alert("无gps轨迹数据");
          return;
        }
        index = 0;
        vali = 0;
        points = [];
        var groupedArray = group(data, 100);

        //alert(groupedArray.length);

        load(groupedArray);
      }
    });
  } else {
    points = [new BMap.Point(114.001, 22.55), new BMap.Point(114.0013, 22.55)];
    //初始化地图,选取第一个点为起始点
    map = new BMap.Map("container");
    map.centerAndZoom(points[0], 15);
    map.enableScrollWheelZoom();
    map.addControl(new BMap.NavigationControl());
    map.addControl(new BMap.ScaleControl());
    map.addControl(new BMap.OverviewMapControl({ isOpen: true }));
    //通过DrivingRoute获取一条路线的point
    var driving = new BMap.DrivingRoute(map);
    //driving.search(new BMap.Point(114.00100, 22.550000), new BMap.Point(113.95100, 22.550000));
    driving.setSearchCompleteCallback(function() {
      //得到路线上的所有point
      points = driving
        .getResults()
        .getPlan(0)
        .getRoute(0)
        .getPath();
      //画面移动到起点和终点的中间
      // centerPoint = new BMap.Point((points[0].lng + points[points.length - 1].lng) / 2, (points[0].lat + points[points.length - 1].lat) / 2);
      // map.panTo(centerPoint);
      //连接所有点
      map.addOverlay(
        new BMap.Polyline(points, {
          strokeColor: "black",
          strokeWeight: 5,
          strokeOpacity: 1
        })
      );
      //显示小车子
      label = new BMap.Label("", { offset: new BMap.Size(-20, -20) });
      car = new BMap.Marker(points[0]);
      car.setLabel(label);
      map.addOverlay(car);
    });
  }
};
// window.play=function() {
// playBtn.disabled = true;
// pauseBtn.disabled = false;

// var point = points[index];
// if(index > 0) {
// map.addOverlay(new BMap.Polyline([points[index - 1], point], {strokeColor: "#000000", strokeWeight:2, strokeOpacity: 2}));
// }
// label.setContent("经度: " + point.lng + "<br>纬度: " + point.lat);
// car.setPosition(point);
// index++;
// if(followChk.checked) {
// map.panTo(point);
// }
// if(index < points.length) {
// timer = window.setTimeout("play(" + index + ")", 200);
// } else {
// playBtn.disabled = true;
// pauseBtn.disabled = true;
// map.panTo(point);
// }
// }

// window.pause=function() {
// playBtn.disabled = false;
// pauseBtn.disabled = true;

// if(timer) {
// window.clearTimeout(timer);
// }
// }

// window.reset=function() {
// followChk.checked = false;
// playBtn.disabled = false;
// pauseBtn.disabled = true;

// if(timer) {
// window.clearTimeout(timer);
// }
// index = 0;
// car.setPosition(points[0]);
// map.panTo(centerPoint);
// }

window.onload = function() {
  var hour = document.getElementById("hourk");
  var min = document.getElementById("hourj");

  for (var b = 0; b < 24; b++) {
    var opt = document.createElement("option");
    opt.value = b;
    opt.innerText = b + ":00";
    hour.appendChild(opt);
  }

  for (var b = 0; b < 24; b++) {
    var opt = document.createElement("option");
    opt.value = b;
    opt.innerText = b + ":00";

    min.appendChild(opt);
  }
};

$(function() {
  $(".btn-primary").click(function() {
    if ($("#device_id").val().length == 0) {
      swal("OMG!", "请输入设备号", "error");

      return;
    }
    if ($("#device_id").val().length == 0) {
      swal("OMG!", "请输入选择日期 ", "error");

      return;
    }
    var isval = false;
    if (parseInt($("#hourj").val()) > parseInt($("#hourk").val())) {
      isval = true;
      //swal("OMG!", "请输入选择日期 ", "error");

      //   return;
    }
    if (!isval) {
      swal("OMG!", "结束时段必须要大于开始时段", "error");

      return;
    }

    init();
  });
});

Date.prototype.Format = function(fmt) {
  //author:wangweizhen
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};
window.group = function(array, subGroupLength) {
  let index = 0;
  let newArray = [];
  while (index < array.length) {
    newArray.push(array.slice(index, (index += subGroupLength)));
  }
  return newArray;
};

window.load = function(groupedArray) {
  for (var i = 0; i < groupedArray.length; i++) {
    //  console.log(groupedArray[i].length);
    var dataval = "";
    for (var k = 0; k < groupedArray[i].length; k++) {
      //for(var j=0; j<groupedArray[i].length; j++){
      //     console.log(groupedArray[i][k].longitude);
      dataval +=
        groupedArray[i][k].longitude + "," + groupedArray[i][k].latitude + ";";
      //}
    }
    dataval = dataval.substring(0, dataval.length - 1);

    // console.log(dataval);
    $.ajax({
      type: "post",
      url:
        "http://api.map.baidu.com/geoconv/v1/?coords=" +
        dataval +
        "&from=1&to=5&ak=D2b4558ebed15e52558c6a766c35ee73",
      data: {},
      async: false,
      dataType: "jsonp",
      //data:{sessionid:sessionStorage.getItem("sid"),devicenumber:"",startTime:"",endTime:""},
      success: function(response) {
        //  console.log(response);
        for (var ii = 0; ii < response.result.length; ii++) {
          //x: 13.91825, y: 22.647102
          // console.log("1:"+response.result[ii].x+","+response.result[ii].y);
          // console.log("2:"+groupedArray[0][ii].longitude+","+groupedArray[0][ii].latitude);
          points.push(
            new BMap.Point(response.result[ii].x, response.result[ii].y)
          );
        }

        vali++;
        if (groupedArray.length == vali) {
          console.log("进入了");
          followChk = document.getElementById("follow");
          playBtn = document.getElementById("play");
          pauseBtn = document.getElementById("pause");
          resetBtn = document.getElementById("reset");

          //初始化地图,选取第一个点为起始点
          map = new BMap.Map("container");
          console.log(points[0]);
          map.centerAndZoom(points[0], 15);
          map.enableScrollWheelZoom();

          map.addControl(new BMap.NavigationControl());
          //scaleCtrl = new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_LEFT,offset: new BMap.Size(10,40)});
          map.addControl(
            new BMap.ScaleControl({
              anchor: BMAP_ANCHOR_BOTTOM_LEFT,
              offset: new BMap.Size(10, 40)
            })
          );
          map.addControl(new BMap.OverviewMapControl({ isOpen: true }));

          //通过DrivingRoute获取一条路线的point
          var driving = new BMap.DrivingRoute(map);
          driving.search(points[0], points[points.length - 1]);

          driving.setSearchCompleteCallback(function() {
            // //得到路线上的所有point
            // points = driving.getResults().getPlan(0).getRoute(0).getPath();
            // //画面移动到起点和终点的中间
            // centerPoint = new BMap.Point((points[0].lng + points[points.length - 1].lng) / 2, (points[0].lat + points[points.length - 1].lat) / 2);
            // map.panTo(centerPoint);
            //连接所有点
            map.addOverlay(
              new BMap.Polyline(points, {
                strokeColor: "red",
                fillColor: "red",
                strokeWeight: 3,
                strokeOpacity: 3
              })
            );

            //    map.addOverlay(new BMap.Polyline(points, {strokeColor: 'red',fillColor:"red", strokeWeight: 3, strokeOpacity: 2}));

            //显示小车子
            var myIcon = new BMap.Icon(
              "static/img/cz.png",
              new BMap.Size(32, 32)
            );
            label = new BMap.Label("", { offset: new BMap.Size(-20, -36) });
            car = new BMap.Marker(points[0], { icon: myIcon });
            car.setLabel(label);
            map.addOverlay(car);

            //点亮操作按钮
            playBtn.disabled = false;
            resetBtn.disabled = false;
            index = 0;
          });
        } else {
          //  var p=groupedArray.length;
          if (vali <= groupedArray.length) {
            load(groupedArray);
          }
        }

        //points = [
        //new BMap.Point(114.00100, 22.550000), new BMap.Point(114.00130, 22.550000),
        //new BMap.Point(114.00160, 22.550000), new BMap.Point(114.00200, 22.550000),
        //new BMap.Point(114.00300, 22.550500), new BMap.Point(114.00400, 22.550000),
        //new BMap.Point(114.00500, 22.550000), new BMap.Point(114.00505, 22.549800),
        //new BMap.Point(114.00510, 22.550000), new BMap.Point(114.00515, 22.550000),
        //new BMap.Point(114.00525, 22.550400), new BMap.Point(114.00537, 22.549500)
        //];
      }
    });
  }
};
window.play = function() {
  // console.log(":"+index)
  playBtn.disabled = true;
  pauseBtn.disabled = false;
  //  console.log(points.length);
  var point = points[index];
  if (index > 0) {
    map.addOverlay(
      new BMap.Polyline([points[index - 1], point], {
        strokeColor: "red",
        strokeWeight: 1,
        strokeOpacity: 1
      })
    );
  }

  if (
    point.lng == points[points.length - 1].lng &&
    point.lat == points[points.length - 1].lat
  ) {
    playBtn.disabled = true;
    pauseBtn.disabled = true;
    if (timer) {
      window.clearTimeout(timer);
    }
  }
  label.setContent("经度: " + point.lng + "<br>纬度: " + point.lat);
  car.setPosition(point);
  index++;
  if (followChk.checked) {
    map.panTo(point);
  }
  if (index < points.length) {
    timer = window.setTimeout("play(" + index + ")", 200);
  } else {
    playBtn.disabled = true;
    pauseBtn.disabled = true;
    map.panTo(point);
  }
};

window.pause = function() {
  playBtn.disabled = false;
  pauseBtn.disabled = true;

  if (timer) {
    window.clearTimeout(timer);
  }
};

window.reset = function() {
  followChk.checked = false;
  playBtn.disabled = false;
  pauseBtn.disabled = true;

  if (timer) {
    window.clearTimeout(timer);
  }
  index = 0;
  car.setPosition(points[0]);
  map.panTo(centerPoint);
};

$("#menuContentdevicesingle").attr("margin"," 0px 65px;  ");
</script>
<style>
@import "../../../../static/css/ztree/metroStyle.css";
label {
  max-width: none;
}
/* #menuContentdevicesingle{
   margin: 0px 65px;  
} */
</style>

<style scoped>
#controller {
  width: 100%;
  border-bottom: 3px outset;
  bottom: 5px;
  height: 38px;
  filter: alpha(Opacity=100);
  -moz-opacity: 1;
  opacity: 1;
  z-index: 10000;
  background-color: lightblue;
}

.allmap {
  width: 100%;

  height: 615px;
  font-family: "微软雅黑";
  border: 1px solid green;
}
.el-tag {
  cursor: pointer;
}
</style>


